package logic

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"iot-base/auth/config"
	"iot-base/auth/svc"
	"sort"
)

var StatusName = map[int]string{
	0: "未知",
	1: "正常",
	2: "校准",
	3: "开机",
	4: "中断恢复",
	5: "诊断",
}

type HisLogic struct {
}

func NewHisLogic() *HisLogic {
	return &HisLogic{}
}

func (l *HisLogic) QueryHis(stationId string, page, size int, classType, startTime, endTime string) ([]map[string]interface{}, error) {
	result, err := svc.Dao.THisData.QueryHisByTime(stationId, page, size, classType, startTime, endTime)
	if err != nil {
		return nil, err
	}
	if result == nil {
		return []map[string]interface{}{}, nil
	}
	temp := map[int64]map[string]interface{}{}
	for index := range result {
		dateTime := result[index].PickTime.Format("2006-01-02 15:04:05")
		key := result[index].PickTime.Unix()
		if _, ok := temp[key]; !ok {
			temp[key] = make(map[string]interface{})
			temp[key]["datetime"] = dateTime
			temp[key]["dateunix"] = result[index].PickTime.Unix()
		}
		temp[key][result[index].ModelID+"#"+result[index].Field] = gin.H{
			"value":  result[index].Value,
			"status": result[index].Status,
		}
	}
	resp := make([]map[string]interface{}, 0, len(temp))
	for _, v := range temp {
		resp = append(resp, v)
	}
	// map 是无序的 需要重新排序
	sort.Slice(resp, func(i, j int) bool {
		return resp[i]["dateunix"].(int64) > resp[j]["dateunix"].(int64)
	})
	return resp, nil
}

func (l *HisLogic) QueryHisTotal(stationId string, classType, startTime, endTime string) (int64, error) {
	return svc.Dao.THisData.QueryHisByTimeCount(stationId, classType, startTime, endTime)
}

func (l *HisLogic) ExcelHis(stationId string, classType, startTime, endTime string) ([]interface{}, error) {
	result, err := svc.Dao.THisData.ExcelHis(stationId, classType, startTime, endTime)
	if err != nil {
		return []interface{}{}, err
	}
	// 数据归类，把相同时间的数据放到一起
	temp := map[int64]map[string]interface{}{}
	for index := range result {
		dateTime := result[index].PickTime.Format("2006-01-02 15:04:05")
		key := result[index].PickTime.Unix()
		if _, ok := temp[key]; !ok {
			temp[key] = make(map[string]interface{})
			temp[key]["datetime"] = dateTime
			temp[key]["dateunix"] = result[index].PickTime.Unix()
		}
		temp[key][result[index].ModelID+"#"+result[index].Field] = gin.H{
			"value":  result[index].Value,
			"status": result[index].Status,
		}
	}
	// map 是无序的 需要重新排序
	resp := make([]map[string]interface{}, 0, len(temp))
	for _, v := range temp {
		resp = append(resp, v)
	}
	sort.Slice(resp, func(i, j int) bool {
		return resp[i]["dateunix"].(int64) > resp[j]["dateunix"].(int64)
	})
	excelData := make([]interface{}, 0, len(result))
	keys := getHisKey()
	// 临时
	for i := range resp {
		interim := make([]interface{}, 0, len(keys)+1)
		interim = append(interim, resp[i]["datetime"])
		for _, key := range keys {
			if v, ok := resp[i][key]; ok {
				value := v.(gin.H)
				interim = append(interim, fmt.Sprintf("%v (%v)", value["value"], getHisDataStatus(value["status"])))
			} else {
				interim = append(interim, "")
			}
		}
		excelData = append(excelData, interim)
	}
	return excelData, nil
}

func getHisKey() []string {
	var resp = make([]string, 0, len(config.HisQueryModelId))
	for _, value := range config.HisQueryModelId {
		if v, ok := config.HisQueryParams[value]; ok {
			for _, v1 := range v {
				resp = append(resp, value+"#"+v1)
			}
		}
	}
	return resp
}

func getHisDataStatus(value interface{}) string {
	var status int
	switch value.(type) {
	case int:
		status = value.(int)
		break
	case int64:
		status = int(value.(int64))
		break
	case int32:
		status = int(value.(int32))
		break
	}
	return StatusName[status]
}
